package com.ywd.platform.netty.jt080.service;

import cn.hutool.core.util.ObjectUtil;
import com.ywd.platform.dto.DeviceDto;
import com.ywd.platform.dto.VehicleDto;
import com.ywd.platform.entity.VehicleTrackRecordEntity;
import com.ywd.platform.netty.jt080.po.AuthBody;
import com.ywd.platform.netty.jt080.po.StatusFlag;
import com.ywd.platform.service.impl.VehicleTrackRecordServiceImpl;
import com.ywd.platform.netty.jt080.po.TerminalRegisterResult;
import com.ywd.platform.service.impl.DeviceServiceImpl;
import com.ywd.platform.service.impl.VehicleServiceImpl;
import com.ywd.platform.netty.jt080.dto.TerminalRegisterDto;
import com.ywd.platform.netty.jt080.po.LocationBody;
import com.ywd.platform.vo.DeviceVo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.UUID;

/**
 * YWD
 * 2025/8/20
 */
@AllArgsConstructor
@Slf4j
@Service
public class TerminalService {

    private final DeviceServiceImpl deviceService;
    private final VehicleServiceImpl vehicleService;
    private final VehicleTrackRecordServiceImpl vehicleTrackRecordService;

    /**
     * 终端设备是否注册
     */
    public DeviceVo isRegister(String terminalPhone) {
        return deviceService.getDeviceBySimCard(terminalPhone);
    }

    /**
     * 终端设备是否鉴权
     */
    public Boolean isAuth(String terminalPhone) {
        DeviceVo deviceVo = deviceService.getDeviceBySimCard(terminalPhone);
        if (ObjectUtil.isEmpty(deviceVo) || ObjectUtil.isEmpty(deviceVo.getAuthCode())) {
            return false;
        }
        return true;
    }

    /**
     * 终端设备注册
     */
    @Transactional(rollbackFor = Exception.class)
    public TerminalRegisterResult registerTerminal(TerminalRegisterDto dto) {

        String authCode = generateAuthCode(dto.getTerminalId());

//        // 1.检查车牌号是否已使用
//        VehicleVo vehicleVo = vehicleService.getVehicleByVehicleNo(dto.getVehicleNo());
//        if(ObjectUtil.isNotEmpty(vehicleVo)){
//            log.error("车牌号已被使用: 车牌号: {}", dto.getVehicleNo());
//        }

        // 2. 设备是否注册
        DeviceVo device = deviceService.getDeviceBySimCard(dto.getTerminalPhone());
        if(ObjectUtil.isNotEmpty(device)){
            return new TerminalRegisterResult(true, device.getAuthCode());
        }

        try {
//            // 3.注册车辆
//            VehicleDto vehicleDto = new VehicleDto();
//            vehicleDto.setPlateColor(dto.getPlateColor())
//                    .setLicensePlate(dto.getLicensePlate());
//            vehicleService.saveVehicle(vehicleDto);
            // 4.注册设备
            DeviceDto deviceDto = new DeviceDto();
            deviceDto.setDeviceUuid(UUID.randomUUID().toString())
                    .setVehicleId(null)    //TODO
                    .setAuthCode(authCode)
                    .setDeviceType(1)
                    .setManufacturer(dto.getManufacturerId())
                    .setModel(dto.getTerminalModel())
                    .setSimCard(dto.getTerminalPhone())
                    .setActivationDate(LocalDateTime.now().toString())
                    .setOnlineStatus(true)
                    .setLastOnlineTime(LocalDateTime.now().toString());

            deviceService.saveDevice(deviceDto);

            //log.info("终端注册成功: 终端ID={}, 终端手机号: {}", dto.getTerminalId(), dto.getTerminalPhone());
            return new TerminalRegisterResult(true, authCode);
        } catch (Exception e) {
            log.error("新增设备失败: {}", e.getMessage());
            return new TerminalRegisterResult(false, e.getMessage());
        }
    }

    /**
     * 生成鉴权码
     */
    public String generateAuthCode(String terminalId) {
        // 生成包含终端ID和随机数的鉴权码
//        return "AUTH-" + terminalId + "-" + UUID.randomUUID().toString().substring(0, 8);
        return UUID.randomUUID().toString().substring(0, 8);
    }

    /**
     * 终端设备鉴权
     */
    public boolean authenticateTerminal(String terminalPhone, AuthBody body) {
        DeviceVo deviceVo = deviceService.getDeviceBySimCard(terminalPhone);
        String authCode = deviceVo.getAuthCode();
        // 验证鉴权码
        if (StringUtils.isNotEmpty(deviceVo.getAuthCode()) && deviceVo.getAuthCode().equals(authCode)) {
            // 更新设备
            deviceService.updatePart(terminalPhone,body);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 处理位置上报
     */
    public Boolean handleLocationReport(String terminalPhone, LocationBody body) {
        //更新设备
        deviceService.updateOnlineStatus(terminalPhone);

        DeviceVo device = deviceService.getDeviceBySimCard(terminalPhone);

        Map<StatusFlag, Boolean> statusMap = body.getStatusMap();
        Boolean vehicleStatus = statusMap.get("VEHICLE_STATUS");

        //保存定位数据
        //车辆
        VehicleTrackRecordEntity vehicleTrackRecordEntity = new VehicleTrackRecordEntity();
        vehicleTrackRecordEntity.setVehicleId(device.getVehicleId());
        vehicleTrackRecordEntity.setDeviceId(device.getId());
        vehicleTrackRecordEntity.setRecordTime(LocalDateTime.now().toString());

        //解析位置信息（TODO）
        //vehicleTrackRecordEntity.setLocation();

        vehicleTrackRecordEntity.setLongitude(body.getLongitude());
        vehicleTrackRecordEntity.setLatitude(body.getLatitude());
        vehicleTrackRecordEntity.setSpeed(BigDecimal.valueOf(body.getSpeed()));
        vehicleTrackRecordEntity.setDirection(body.getDirection());
        vehicleTrackRecordEntity.setAltitude(BigDecimal.valueOf(body.getAltitude()));
        if(ObjectUtil.isNotEmpty(vehicleStatus) && vehicleStatus){
            vehicleTrackRecordEntity.setIgnitionStatus(1);
        }else {
            vehicleTrackRecordEntity.setIgnitionStatus(0);
        }
        //保存定位
        return vehicleTrackRecordService.save(vehicleTrackRecordEntity);
    }


    /**
     * 处理心跳(0x0002)
     */
    public Boolean updateTerminalActiveTime(String terminalPhone) {
        return deviceService.updateOnlineStatus(terminalPhone);
    }

}
